package xuser

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xnum"
)

// 创建用户附加属性
//
//	uid	用户ID
//	tid	类型ID
//	val	附加属性值
func CreateAdditional(uid, tid uint, val string) error {
	tmp, err := GetAdditional(uid, tid)
	if err != nil {
		return err
	}
	if xnum.InArray(val, tmp) {
		return nil
	}
	// 创建关联
	err = _default.DB.Table(_default.AdditionalPropertyTable).Create(&UserAdditional{
		UserId:    uid,
		TypeId:    tid,
		Value:     val,
		CreatedAt: time.Now().Format(time.DateTime),
	}).Error
	if err != nil {
		return xlog.AE("用户附加属性创建失败", err)
	}
	tmp = append(tmp, val)
	xcache.SetStruct(xcache.Key("xuser.get.additional", uid, tid), tmp)
	// 添加属性列表-0
	uids := AdditionalUsers(0, val)
	uids = append(uids, uid)
	xcache.SetStruct(xcache.Key("xuser.additional.users", uint(0), val), uids)
	// 添加属性列表-tid
	uids = AdditionalUsers(tid, val)
	uids = append(uids, uid)
	xcache.SetStruct(xcache.Key("xuser.additional.users", tid, val), uids)
	return nil
}
